#!/usr/bin/env python
# -*- coding: utf-8 -*-

# import os
import md5
import bottle

#HTML = "output"
HTML = "/home/zhwei/blog"

global status
status = 0
bucket = dict()

def get_real_path(path):
    return HTML + path

def get_md5(path):

    path=get_real_path(path)
    _key = md5.new()
    _key.update(path)
    return _key.hexdigest()

def get_content(path):
    with open(get_real_path(path)) as fi:
        return fi.read()

def get_path_md5(path):

    _key = md5.new()
    _key.update(get_content(path))

    return _key.hexdigest()


def get_set(path):

    if bucket.has_key(path):
        return bucket[path][0]
    else:
        try:
            content=get_content(path)
        except IOError:
            bottle.abort(404)
        bucket[path]=(content, get_path_md5(path))
        return content


def check():
    for path in bucket:
        if bucket[path][1] != get_path_md5(path):
            try:
                bucket[path]=(get_content(path), get_path_md5(path))
            except IOError:
                pass


@bottle.hook('after_request')
def after():
    global status
    status += 1
    if status >= 7:
        check()
        status = 0


@bottle.route('<path:re:.*\.html|\/>')
def cache(path):

    if path=='/':path='/index.html'

    return get_set(path)

@bottle.error(404)
@bottle.error(500)
def cache_error(error):
    return "Error! <a href='/'>INDEX</a>"


@bottle.route('<filename:path>')
def send_static(filename):
    return bottle.static_file(filename, root=HTML)

if '__main__' == __name__:
    # bottle.run(host='0.0.0.0', port=1267, debug=True)
    bottle.run(host='0.0.0.0', port=1267)
